﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace ExcellOnServices.Models.Utils
{
	public class CacheHelper
	{
		public static readonly string PRODUCTS_KEY = "products";
		public static readonly DateTime PRODUCTS_ABSOLUTE_EXPIRATION = DateTime.Now.AddMinutes(5);
		public static readonly string CATEGORIES_KEY = "categories";
		public static readonly DateTime CATEGORIES_ABSOLUTE_EXPIRATION = DateTime.Now.AddMinutes(30);

		public static List<Product> getProductList(ExcellOnServicesContext db) {
			List<Product> products = HttpRuntime.Cache.Get(CacheHelper.PRODUCTS_KEY) as List<Product>;
			if (products == null) {
				products = db.Products.ToList();
				HttpRuntime.Cache.Insert(CacheHelper.PRODUCTS_KEY, products, null, CacheHelper.PRODUCTS_ABSOLUTE_EXPIRATION, System.Web.Caching.Cache.NoSlidingExpiration);
			}

			return products;
		}

		public static List<Category> getCategoryList(ExcellOnServicesContext db) {
			List<Category> categories = HttpRuntime.Cache.Get(CacheHelper.CATEGORIES_KEY) as List<Category>;
			if (categories == null) {
				categories = db.Categories.ToList();
				HttpRuntime.Cache.Insert(CacheHelper.CATEGORIES_KEY, categories, null, CacheHelper.CATEGORIES_ABSOLUTE_EXPIRATION, System.Web.Caching.Cache.NoSlidingExpiration);
			}

			return categories;
		}

		public static void clearCache() {
			HttpRuntime.Cache.Remove(PRODUCTS_KEY);
			HttpRuntime.Cache.Remove(CATEGORIES_KEY);
		}
	}
}